//
//  YFGoldPriceChatView.m
//  HSJCIOS
//
//  Created by zyf on 16/8/10.
//  Copyright © 2016年 zc. All rights reserved.
//

#import "YFGoldPriceChatView.h"
#import "YFLineTipView.h"
#import "GoldPriceTrendModel.h"

@interface YFGoldPriceChatView ()

@property (nonatomic, strong) CAShapeLayer    *dotLayer;
@property (nonatomic, strong) NSMutableArray  *dotXArray;
@property (nonatomic, strong) NSMutableArray  *pointYArray;
@property (nonatomic, strong) CAShapeLayer    *lineChartLayer;
@property (nonatomic, strong) YFLineTipView   *lineTipView;
@property (nonatomic, assign) CGFloat         rowHeight;
@property (nonatomic, assign) CGFloat         bottomHeight;

@end

@implementation YFGoldPriceChatView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor   = [UIColor whiteColor];
        self.lineTipView       = [[YFLineTipView alloc] init];
        self.dotXArray = [NSMutableArray array];
        self.pointYArray       = [NSMutableArray array];
        self.rowHeight         = 0;
        self.bottomHeight      = 20;
        
        self.dotLayer = [CAShapeLayer layer];
    }
    return self;
}

- (void)setVerticalDateArray:(NSArray *)verticalDateArray {
    _verticalDateArray = verticalDateArray;
    [self createLabelY];
}


- (void)setHorizontalDateArray:(NSArray *)horizontalDateArray {
    _horizontalDateArray = horizontalDateArray;
}

- (void)setDataArray:(NSArray *)dataArray {
    _dataArray = dataArray;
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
    [self.dotXArray removeAllObjects];
    [self setNeedsDisplay];
    [self createLabelX];
    [self createLabelY];
    
    [self dravLine];
}

- (void)createLabelY {
    NSInteger count = _verticalDateArray.count;
    CGFloat width   = 50;
    CGFloat height  = 11;
    CGFloat x       = 15;
    CGFloat rowHeight = (self.frame.size.height - self.bottomHeight) / count;
    self.rowHeight = rowHeight;
    for (int i = 0; i < count; i ++) {
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, rowHeight * i + (rowHeight - height), width, height)];
        label.text = _verticalDateArray[count - i - 1];
        label.font = [UIFont systemFontOfSize:10];
        label.textColor = [UIColor blackColor];
        [self addSubview:label];
    }
}

- (void)createLabelX {
    NSInteger count = _horizontalDateArray.count;
    CGFloat width   = (self.width - 30) / (count - 1);
    CGFloat y       = self.frame.size.height - self.bottomHeight;
    
    for (int i = 0; i < count; i ++) {
        NSString *text = _horizontalDateArray[i];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(width * i, y, width, 12)];
        label.tag = 1000 + i;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:10];
        [self addSubview:label];
        label.textColor = [UIColor lightGrayColor];
        
        if (self.allPointCount == 28 ||//30
            self.allPointCount == 168) {//7
            
            label.text = [NSString stringWithFormat:@"%@日",[_horizontalDateArray[i] substringWithRange:NSMakeRange(8, 2)]];
            
            NSInteger dataCount = _dataArray.count;
            NSInteger index = 0;
            for (NSInteger z = 0; z < dataCount; z++) {
                 GoldPriceTrendModel *model = _dataArray[z];
                NSString *time = model.days;
                NSString *text2 = [NSString stringWithFormat:@"%@01:00",[text substringToIndex:11]];
                NSString *text3 = [NSString stringWithFormat:@"%@02:00",[text substringToIndex:11]];
                NSString *text4 = [NSString stringWithFormat:@"%@03:00",[text substringToIndex:11]];
                NSString *text5 = [NSString stringWithFormat:@"%@04:00",[text substringToIndex:11]];
                if ([time isEqualToString:text]) {
                    index = z;
                    break;
                } else if ([time isEqualToString:text2]) {
                    index = z;
                    break;
                }else if ([time isEqualToString:text3]) {
                    index = z;
                    break;
                }else if ([time isEqualToString:text4]) {
                    index = z;
                    break;
                }else if ([time isEqualToString:text5]) {
                    index = z;
                    break;
                }
            }
           
            label.centerX = 15 + (self.width - 30)/self.allPointCount*index;
        }else {//24
            label.text = _horizontalDateArray[i];
            label.centerX = 15 + width *i;
        }
        
        
//
//        label.centerX = 15 + (self.width - 30)/self.allPointCount*i
    }
}


- (void)dravLine
{
    [self.pointYArray removeAllObjects];
    
    NSInteger count = _dataArray.count;
    GoldPriceTrendModel *model = [_dataArray firstObject];
    
    CGFloat minY      = [[_verticalDateArray firstObject] floatValue];
    CGFloat maxY      = [[_verticalDateArray lastObject] floatValue];
    CGFloat dataY     = [model.all_num floatValue];
    CGFloat height    = self.frame.size.height - self.bottomHeight - self.rowHeight;
    
    CGFloat pointY    = (1 - (dataY - minY)/(maxY - minY)) * height + self.rowHeight;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(15, pointY)];
    
    [self.pointYArray addObject:@(pointY)];
    [self.dotXArray addObject:@(15)];
    for (int i = 1; i < count; i ++) {
        GoldPriceTrendModel *model = _dataArray[i];
        dataY = [model.all_num floatValue];
        pointY = (1 - (dataY - minY)/(maxY - minY)) * height + self.rowHeight;
        [self.pointYArray addObject:@(pointY)];
        CGFloat x = (self.width - 30)/self.allPointCount*i + 15;
        [path addLineToPoint:CGPointMake(x, pointY)];
        [self.dotXArray addObject:@(x)];
    }
    
    self.lineChartLayer = [CAShapeLayer layer];
    self.lineChartLayer.path = path.CGPath;
    self.lineChartLayer.strokeColor = [UIColor orangeColor].CGColor;
    self.lineChartLayer.fillColor = [[UIColor clearColor] CGColor];
    self.lineChartLayer.lineWidth = 0;
    [self.layer addSublayer:self.lineChartLayer];
    
    self.lineChartLayer.lineWidth = 0.8;
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration            = 1.0;
    pathAnimation.repeatCount         = 1;
    pathAnimation.removedOnCompletion = YES;
    pathAnimation.fromValue           = @0;
    pathAnimation.toValue             = @1;
    [self.lineChartLayer addAnimation:pathAnimation forKey:@"strokeEnd1"];
    
}


//画坐标
- (void)drawRect:(CGRect)rect
{
    //最下面的距离
    CGFloat majorDown = self.bottomHeight;
    NSInteger count   = _verticalDateArray.count;
    //行高
    CGFloat rowHeight = (rect.size.height - majorDown) / count;
    //x起点
    CGFloat xStart    = 15;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    for (int i = 1; i <= count ; i ++) {
        [path moveToPoint:CGPointMake(xStart, i * rowHeight)];
        [path addLineToPoint:CGPointMake(rect.size.width - xStart, i * rowHeight )];
    }
    [path setLineWidth:0.1f];
    [[UIColor blackColor] set];
    [path stroke];
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint curP = [[touches anyObject] locationInView:self];
    [self changView:curP];
}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint curP = [[touches anyObject] locationInView:self];
    [self changView:curP];
}

//改变坐标
- (void)changView:(CGPoint )curP
{
    CGFloat curPX = curP.x;
    
    CGFloat minX = [[self.dotXArray firstObject] floatValue];
    CGFloat maxX = [[self.dotXArray lastObject] floatValue];
    if (curPX < minX) {
        curPX = minX;
    }else if(curPX > maxX){
        curPX = maxX;
    }
    NSArray *array = [self changeArray:self.dotXArray value:curPX];
    NSInteger index = [array indexOfObject:@(curPX)];
    if (index == 0) {
        curPX = [array[index] floatValue];
    }else if(index > (self.pointYArray.count - 1)){
        index = self.pointYArray.count - 1;
        curPX = [array[index] floatValue];
    }else{
        float last = [array[index - 1] floatValue];
        float next = [array[index + 1] floatValue];
        float one = ABS(last - curPX);
        float two = ABS(next - curPX);
        if (one > two) {
            curPX = next;
            index = index;
        } else {
            curPX = last;
            index = index - 1;
        }
    }
    
    CGFloat tipH     = (36);
    CGFloat tipHhalf = tipH * 0.5;
    CGFloat marjorW  = 7;
    CGFloat tipX     = curPX + marjorW;
    CGFloat tipY     = [self.pointYArray[index] floatValue] - tipHhalf;
    CGFloat tipW     = (114);
    NSUInteger tipType = YFLineTipTypeRight;
    
    //最右边距离不够时，居左显示
    if ((self.frame.size.width - curPX) < (tipW + marjorW)) {
        tipX = curPX - marjorW - tipW;
        tipType = YFLineTipTypeLeft;
    }
    
    CGFloat tipMinY = 0;
    CGFloat tipMaxY = self.frame.size.height - self.bottomHeight - tipHhalf;
    
    if (tipY <= tipMinY) {
        tipY = 0;
    } else if (tipY >= tipMaxY) {
        tipY = tipMaxY - tipHhalf;
    }
    
    self.lineTipView.frame = CGRectMake(tipX, tipY, tipW, tipH);
    GoldPriceTrendModel *model = self.dataArray[index];
    self.lineTipView.valueString = [NSString stringWithFormat:@"%.2f",[model.all_num floatValue]];
    self.lineTipView.timeString = model.days;
    self.lineTipView.tag = 20160808;
    self.lineTipView.arrowType = tipType;
    
    UIBezierPath *dotPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(curPX - 4, [self.pointYArray[index] floatValue] - 4, 8, 8)];
    self.dotLayer.path = dotPath.CGPath;
    self.dotLayer.fillColor = [UIColor orangeColor].CGColor;
    
    if (![self viewWithTag:20160808]) {
        [self addSubview:self.lineTipView];
        [self.layer addSublayer:self.dotLayer];
    }
}

//快速排序
- (NSArray *)changeArray:(NSMutableArray *)array value:(CGFloat )value {
    NSMutableArray *mut = [NSMutableArray arrayWithArray:array];
    [mut addObject:@(value)];
    NSArray *temp = [mut sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        if ([obj1 floatValue] < [obj2 floatValue]) {
            return NSOrderedDescending;
        }
        if ([obj1 floatValue] > [obj2 floatValue]) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
    return temp;
}

@end
